package cat.music.ut.ui.fragment

import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import cat.music.ut.adapter.DownloadRecordAdapter
import cat.music.ut.base.BaseFragment
import cat.music.ut.comm.ext.setEmptyView
import cat.music.ut.databinding.FragmentIndexBinding
import cat.music.ut.ui.activity.MusicActivity
import cat.music.ut.ui.activity.PlayerMusic
import com.arialyy.aria.core.Aria
import com.arialyy.aria.core.download.DownloadEntity
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class IndexFragment : BaseFragment<FragmentIndexBinding>(),DownloadRecordAdapter.Listener {
    private val mActivity by lazy { requireActivity() as MusicActivity }
    val data = mutableListOf<DownloadEntity>()
    private val mDownloadRecordAdapter by lazy { DownloadRecordAdapter(requireActivity(),data) }
    override fun getViewBinding(): FragmentIndexBinding {
        return FragmentIndexBinding.inflate(layoutInflater)
    }

    override fun initView() {
        mDownloadRecordAdapter.listener = this
        vb.rvDownloadList.layoutManager = LinearLayoutManager(requireActivity())
        vb.rvDownloadList.adapter = mDownloadRecordAdapter
        vb.rvDownloadList.setEmptyView()
    }

    override fun observe() {

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EventBus.getDefault().register(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
    override fun initData() {
        data.clear()
        val allCompleteTask = Aria.download(this).allCompleteTask?: mutableListOf()
        data.addAll(allCompleteTask)
        mDownloadRecordAdapter.notifyDataSetChanged()
    }

    override fun initClick() {

    }

    private fun startLive() {

    }

    override fun clickItem(data: DownloadEntity) {
        EventBus.getDefault().post(PlayerMusic(data.filePath,data.fileName))
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun upload(data: DownloadEntity){
        initData()
    }

    override fun onResume() {
        super.onResume()
        initData()
    }
}